package com.reeygu.base.entity;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 定制化顺序执行 打印结果A B C A B 。。。
 */
public class ShareResource {
    // 1 = A , 2 = B , 3 = C
    private int flag = 1;
    private final Lock lock = new ReentrantLock();
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();
    private final Condition conditionC = lock.newCondition();

    //conditionA 接收到 flag = 1， 执行打印 A 业务
    public void returnA() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 1) {
                conditionA.await();
            }
            System.out.println("A");
            flag = 2;
            conditionB.signal();
        } finally {
            lock.unlock();
        }
    }

    //conditionB 接收到 flag = 3， 执行打印 B 业务
    public void returnB() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 2) {
                conditionB.await();
            }
            System.out.println("B");
            flag = 3;
            conditionC.signal();
        } finally {
            lock.unlock();
        }
    }

    //conditionC 接收到 flag = 3， 执行打印 C 业务
    public void returnC() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 3) {
                conditionC.await();
            }
            System.out.println("C");
            flag = 1;
            conditionA.signal();
        } finally {
            lock.unlock();
        }
    }
}
